<template>
  <el-container>
    <el-header
      style="height: 8vh; max-height: 8vh;"
      v-bind:style="{ background: color1 }"
    >
      <div style="float: left;border: none; margin-top: 10px;">
        <el-color-picker
          style="float: left;border: none;"
          v-model="color1"
        ></el-color-picker>
      </div>
      <div class="grid-content">
        <div class="demo-type">
          <div>
            <el-avatar
              src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
            ></el-avatar>
          </div>
        </div>
        <el-dropdown :hide-on-click="false">
          <i class="el-icon-setting" style="color: #fff;margin-right: 15px"></i>
          <el-dropdown-menu slot="dropdown" :hide-after="0">
            <el-dropdown-item>{{ ruleForm.name }}</el-dropdown-item>
            <el-dropdown-item>{{ ruleForm.region3 }}</el-dropdown-item>
            <el-dropdown-item>{{ ruleForm.region }}</el-dropdown-item>

            <el-tooltip placement="top" style="border: none;" :hide-after="0">
              <!-- <div
                slot="content"
                style="display: flex; justify-content: center; align-items: center;"
              >
                python课程设计<br />数据库概论<br />马克思主义概论
              </div>
              <el-button>我的课程</el-button> -->
            </el-tooltip>
            <el-dropdown-item>
              <el-popconfirm title="确认退出登录？">
                <el-button slot="reference" style="border: none;" @click="exit"
                  >退出</el-button
                >
              </el-popconfirm>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div></el-header
    >
    <el-main>
      <div class="datatop">
        <!-- 按钮部分 -->
        <div style="display: flex; margin-top: 30px;">
          <!-- 最高低分按钮显示样式 -->
          <!-- <div style="margin-right: 30px;">
            <el-button @click="show3 = !show3" style="margin-bottom: 10px;"
              >Limit points</el-button
            >
            <el-collapse-transition>
              <div v-show="show3">
                <div
                  class="transition-box"
                  v-bind:style="{ background: color1 }"
                >
                  minimum：
                </div>
              </div>
            </el-collapse-transition>
          </div> -->
          <!-- 平均分按钮显示样式 -->
          <div>
            <el-button @click="show1 = !show1" style="margin-bottom: 10px;"
              >Average score</el-button
            >
            <el-collapse-transition>
              <div v-show="show1">
                <div
                  class="transition-box"
                  v-bind:style="{ background: color1 }"
                >
                  average：{{ avg }}
                </div>
              </div>
            </el-collapse-transition>
          </div>
          <!-- 不及格人数按钮样式 -->
          <div style="margin-left: 30px;">
            <el-button @click="show2 = !show2" style="margin-bottom: 10px;"
              >Failing Grades</el-button
            >
            <el-collapse-transition>
              <div v-show="show2">
                <div
                  class="transition-box"
                  v-bind:style="{ background: color1 }"
                >
                  numbers：{{ failgrade }}
                </div>
              </div>
            </el-collapse-transition>
          </div>
          <!-- 学分样式 -->
          <div style="margin-left: 30px;">
            <el-button @click="show4 = !show4" style="margin-bottom: 10px;"
              >Geted Credit</el-button
            >
            <el-collapse-transition>
              <div v-show="show4">
                <div
                  class="transition-box"
                  v-bind:style="{ background: color1 }"
                >
                  credit：{{ csum }}
                </div>
              </div>
            </el-collapse-transition>
          </div>
        </div>

        <!-- 个人信息 -->
        <div class="myMessage">
          <el-descriptions title="">
            <el-descriptions-item label="姓名">{{
              ruleForm.name
            }}</el-descriptions-item>
            <el-descriptions-item label="学号">{{
              studentId
            }}</el-descriptions-item>
            <!-- <el-descriptions-item label="性别">女</el-descriptions-item> -->
            <el-descriptions-item label="出生日期">{{
              ruleForm.date1
            }}</el-descriptions-item>
            <el-descriptions-item label="系">{{
              ruleForm.region2
            }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{
              ruleForm.region3
            }}</el-descriptions-item>
            <el-descriptions-item label="班级">
              {{ ruleForm.region }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- 修改个人信息的抽屉 -->

        <el-drawer
          :visible.sync="drawer"
          :direction="direction"
          :withHeader="false"
          size="60%"
        >
          <div style="height: 100%; width: 100%;margin-top: 20px;">
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="姓名" prop="name" style="width: 500px;">
                <el-input v-model="ruleForm.name" disabled></el-input>
              </el-form-item>
              <el-form-item label="系部" prop="region2">
                <el-input v-model="ruleForm.region2" disabled></el-input>
                <!-- <el-select
                  v-model="ruleForm.region2"
                  placeholder="请选择你所在的系"
                >
                  <el-option label="计算机系" value="shanghai" disabled></el-option>
                  <el-option label="金融系" value="beijing" disabled></el-option>
                </el-select> -->
              </el-form-item>

              <el-form-item label="专业" prop="region3">
                <el-input v-model="ruleForm.region3" disabled></el-input>
                <!-- <el-select
                  v-model="ruleForm.region3"
                  placeholder="请选择你所在的专业"
                >
                  <el-option label="人工智能" value="shanghai"></el-option>
                  <el-option
                    label="计算机科学与技术"
                    value="beijing"
                  ></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="班级" prop="region">
                <el-input v-model="ruleForm.region" disabled></el-input>
                <!-- <el-select
                  v-model="ruleForm.region"
                  placeholder="请选择你所在的班级"
                >
                  <el-option label="211班" value="shanghai"></el-option>
                  <el-option label="212班" value="beijing"></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="出生日期" required>
                <el-col :span="11">
                  <el-form-item prop="date1">
                    <el-date-picker
                      type="date"
                      format="yyyy-MM-dd"
                      placeholder="选择日期"
                      v-model="ruleForm.date1"
                      style="width: 100%;"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col class="line" :span="2">-</el-col>
              </el-form-item>
              <el-form-item label="性别" prop="resource">
                <el-radio-group v-model="ruleForm.resource">
                  <el-radio label="男"></el-radio>
                  <el-radio label="女"></el-radio>
                  <el-radio label="未知"></el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item>
                <el-button
                  @click="submitForm"
                  v-bind:style="{ background: color1 }"
                  style="color: #fff;"
                  >确认</el-button
                >
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-drawer>
        <div
          style="display: flex;flex-direction: column;justify-content: center;"
        >
          <el-button
            icon="el-icon-edit"
            circle
            size="mini"
            style="float: left;color: #fff;"
            @click="drawer = true"
            v-bind:style="{ background: color1 }"
          ></el-button>
        </div>
      </div>
      <el-divider></el-divider>
      <!-- <button @click="grade_view">看成绩</button> -->

      <!-- 学期框 -->
      <el-cascader
        style="width: 30vh;"
        :props="{ expandTrigger: 'hover' }"
        placeholder="全学年"
        :options="options"
        clearable
        @change="handleChange"
      ></el-cascader>

      <div class="myscore">
        <el-table
          :data="tableData"
          style="width: 100%;min-height: 380px;"
          :row-class-name="tableRowClassName"
          :height="420"
          ><el-table-column
            prop="gradeId"
            label="成绩id"
            width="200"
          ></el-table-column>
          <!-- <el-table-column prop="name" label="姓名" width="180">
          </el-table-column> -->
          <el-table-column prop="courseId" label="课程号" width="180">
          </el-table-column
          ><el-table-column prop="courseName" label="课程名" width="300">
          </el-table-column>
          ><el-table-column prop="courseCredit" label="学分" width="180">
          </el-table-column>
          <el-table-column prop="gradeSemester" label="学年" width="180">
          </el-table-column>
          <el-table-column prop="gradeResult" label="成绩" width="180">
          </el-table-column>
          <!-- <el-table-column prop="avg" label="平均分" width="180">
          </el-table-column> -->
        </el-table>
      </div>
      <!-- 导出打印成绩按钮 -->
      <div style="display: flex; justify-content: space-around;width: 60%;">
        <!-- 成绩导出 -->
        <el-button plain type="primary" @click="exportScore"
          >导出当前成绩</el-button
        >
        <!-- <el-button
          type="warning"
          size="mini"
          @click="exportScore"
          style="width: 100px;"
          >导出当前成绩</el-button
        > -->
        <!-- 打印 -->
        <el-button
          size="mini"
          class="el-icon-printer"
          @click="printJson"
        ></el-button>
      </div>
    </el-main>
    <el-footer style="height: 4vh;" v-bind:style="{ background: color1 }">
    </el-footer>
  </el-container>
</template>
<script>
import { s_request } from "../network/request";
import printJS from "print-js";
// import { ElMessageBox } from 'element-plus'
export default {
  data() {
    return {
      avg: 0,
      csum: 0,
      failgrade: 0,
      tableData: [],
      // 请求成绩传参
      studentId: "",
      gradeSemester: 0,

      // 学期选择
      options: [
        {
          value: "hh",
          label: "全学年"
        },
        {
          value: "zhinan",
          label: "大一学年",
          children: [
            {
              value: 1,
              label: "春季学期"
            },
            {
              value: 2,
              label: "秋季学期"
            }
          ]
        },
        {
          value: "zujian",
          label: "大二学年",
          children: [
            {
              value: 3,
              label: "春季学期"
            },
            {
              value: 4,
              label: "秋季学期"
            }
          ]
        },
        {
          value: "ziyuan",
          label: "大三学年",
          children: [
            {
              value: 5,
              label: "春季学期"
            },
            {
              value: 6,
              label: "秋季学期"
            }
          ]
        },
        {
          value: "ziyuan",
          label: "大四学年",
          children: [
            {
              value: 7,
              label: "春季学期"
            },
            {
              value: 8,
              label: "秋季学期"
            }
          ]
        }
      ],

      // 表单提交及验证所需数据
      studentId: "",
      ruleForm: {
        name: "",
        region: "",
        date1: "",
        delivery: false,
        resource: "",
        region2: "",
        region3: ""
      },
      rules: {
        // name: [
        //   { required: true, message: "请输入姓名", trigger: "blur" },
        //   { min: 3, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        // ],
        // region: [{ required: true, message: "请选择班级", trigger: "change" }],
        // region2: [{ required: true, message: "请选择系部", trigger: "change" }],
        // region3: [{ required: true, message: "请选择专业", trigger: "change" }],
        date1: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        resource: [{ required: true, message: "请选择性别", trigger: "change" }]
      },
      // 控制抽屉从上往下开
      drawer: false,
      direction: "ttb",
      // 按钮打开参数
      show3: false,
      show2: false,
      show1: false,
      show4: false,
      // 数据
      //   like: true,
      value1: 3,
      value2: 18,
      value3: 20.5,

      // 颜色选择器
      color1: "#2d3a4b"
      //   成绩数据
    };
  },
  methods: {
    // 表单提交事件
    submitForm() {
      // 修改信息请求
      function timeAdd0(num) {
        var str = num.toString();
        if (str.length <= 1) {
          str = "0" + str;
        }
        return str;
      }
      function formatterDate(date) {
        let result = new Date(date);
        return result;
      }
      var d = formatterDate(this.ruleForm.date1);

      //  = this.ruleForm.date1
      d =
        d.getFullYear() +
        "-" +
        timeAdd0(d.getMonth() + 1) +
        "-" +
        timeAdd0(d.getDate());
      console.log(this.ruleForm.resource);
      this.ruleForm.date1 = d;

      s_request({
        url: "/student/updateByStudent",
        method: "post",
        data: {
          studentId: this.studentId,
          studentGender: this.ruleForm.resource,
          studentBirth: this.ruleForm.date1
        }
      })
        .then(res => {
          console.log(res);
          // 验证正确实现页面跳转
          if (res.code == 200) {
            // alert("Success!");
            this.open2();
          }
        })
        .catch(err => {
          console.log(err);
        });
      // this.$refs[formName].validate(valid => {
      //   if (valid) {
      //     alert("submit!");
      //     console
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
    },
    // 重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 修改用户数据的界面
    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then(_ => {
    //       done();
    //     })
    //     .catch(_ => {});
    // },
    // 更改自己信息的弹窗
    open2() {
      this.$message({
        message: "修改成功",
        type: "success"
      });
    },
    open() {
      this.$confirm(
        "检测到未保存的内容，是否在离开页面前保存修改？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "保存",
          cancelButtonText: "放弃修改"
        }
      )
        .then(() => {
          this.$message({
            type: "info",
            message: "保存修改"
          });
        })
        .catch(action => {
          this.$message({
            type: "info",
            message:
              action === "cancel" ? "放弃保存并离开页面" : "停留在当前页面"
          });
        });
    },
    // 危险成绩提示
    tableRowClassName({ row, rowIndex }) {
      if (row.score < 60) {
        return "warning-row";
      } else if (row.score > 90) {
        return "success-row";
      }
      return "";
    },

    // 获取成绩
    handleChange(value) {
      console.log(value[1]);
      // if (value && value[0] && value[1] && value[2]) {
      this.gradeSemester = value[1];
      // }
      if (this.gradeSemester == undefined) {
        this.gradeSemester = 0;
      }
      s_request({
        url: "/student/getGrade/" + this.studentId + "/" + this.gradeSemester,
        method: "get"
      })
        .then(res => {
          console.log(res);

          if (res.code == 200) {
            console.log("请求到成绩");
            console.log(res.data);
            this.tableData = res.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 清空缓存退出登录
    exit() {
      localStorage.clear();
      this.$router.push({ path: "/login" });
    },

    // 导出当前成绩
    exportScore() {
      function transData(sourceData) {
        // 定义一个空数组 - 最后处理后返回的还是一个数组,return出来的
        let newArr = [];
        //对源数据进行循环遍历
        sourceData.forEach(item => {
          //item 是遍历出来的每一条对象 => { name: "张三", age: 18 }
          //用Object.values()方法 拿到每个对象的value值 - 组成一个新的数组
          const arr = Object.values(item); // arr就是新组成的 => ['张三', 18]
          // console.log(22,arr)
          // 将新的小数组 添加到 一个大数组中
          newArr.push(arr);
        });
        return newArr;
      }

      let res = transData(this.tableData);
      console.log(res);

      // 动态引入 @/vendor/Export2Excel 文件
      import("../../vendor/Export2Excel").then(excel => {
        // excel：是 @/vendor/Export2Excel 文件中导出的模块
        // export_json_to_excel：将 js 数据转换为 excel
        excel.export_json_to_excel({
          // 表头 header 必填，是一个数组
          header: ["成绩id", "课程号", "课程名", "学分", "学期", "成绩"],
          // 表格 body 具体数据，是一个二维数组
          data: res,
          filename: this.ruleForm.name + "成绩表", // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: "xlsx" // 生成的文件类型
        });
      });
    },

    // 打印成pdf
    printJson() {
      printJS({
        printable: this.tableData, //this.list是从后台接口获取的数据，未展示
        properties: [
          { field: "gradeId", displayName: "成绩ID" },
          { field: "courseId", displayName: "课程号" },
          { field: "courseName", displayName: "课程名" },
          { field: "courseCredit", displayName: "学分" },
          { field: "gradeSemester", displayName: "学期" },
          { field: "gradeResult", displayName: "成绩" }
        ],
        type: "json",
        header: this.ruleForm.name + "成绩信息"
      });
    }
  },
  // 刚挂起的时候取数据
  mounted() {
    this.studentId = JSON.parse(localStorage.getItem("userid"));
    this.ruleForm.name = JSON.parse(localStorage.getItem("studentName"));
    this.ruleForm.date1 = JSON.parse(localStorage.getItem("studentBirth"));
    this.ruleForm.resource = JSON.parse(localStorage.getItem("studentGender"));
    this.ruleForm.region2 = JSON.parse(
      localStorage.getItem("studentDepartmentName")
    );
    this.ruleForm.region3 = JSON.parse(
      localStorage.getItem("studentMajorName")
    );
    this.ruleForm.region = JSON.parse(localStorage.getItem("studentClassName"));

    // 刚挂起时默认请求0
    s_request({
      url: "/student/getGrade/" + this.studentId + "/" + 0,
      method: "get"
    })
      .then(res => {
        console.log(res);

        if (res.code == 200) {
          console.log("请求到成绩");
          console.log(res.data);
          this.tableData = res.data;
        }
        let sums = 0,
          i = 0,
          sumc = 0,
          count = 0;
        this.tableData.forEach((item, index) => {
          sums = sums + item.gradeResult;
          sumc = sumc + item.courseCredit;
          i = i + 1;
          if (item.gradeResult < 60) {
            count = count + 1;
          }
        });
        this.avg = (sums / i).toFixed(2);
        this.csum = sumc;
        this.failgrade = count;
      })
      .catch(err => {
        console.log(err);
      });
  }
};
</script>
<style>
/* 抽屉样式 */
.myMessage {
  width: 35%;
  margin-top: 20px;
  max-height: 100px;
  overflow: hidden;
}
.datatop {
  display: flex;
  max-height: 140px;
  flex-direction: row;
  justify-content: space-around;
}
/* 最高低分按钮显示样式 */
.transition-box {
  margin-bottom: 10px;
  width: 150px;
  height: 50px;
  border-radius: 4px;
  /* background-color: #2b5c99; */
  text-align: center;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  /* font-family: "PMZD"; */

  /* padding: 30px 10px; */
  box-sizing: border-box;
  margin-right: 20px;
}
.myData {
  font-size: larger;
  display: flex;
  justify-content: space-around;
}
/* 表格位置 */
.myscore {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  /* height: 200px; */
  /* overflow: scroll; */
}
/* 表格危险颜色样式 */
.el-table .warning-row {
  background: rgba(255, 228, 223, 0.707);
}

.el-table .success-row {
  background: #f0f9eb;
}
/* 主题选择器 */
.el-color-picker__trigger {
  border: none;
}
.grid-content {
  /* background-color: #333; */
  float: right;
  display: flex;
  /* justify-items: end; */
  align-items: end;
  margin-top: 10px;
}

.el-main {
  padding-top: 0;
  padding-bottom: 0;
  height: 88vh;
  display: flex;
  /* align-content: end; */
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
}
.el-input.is-disabled .el-input__inner {
  width: 300px;
}
</style>
